package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/wena-dev/proxy"
)

func main() {
	log.SetFlags(log.Lshortfile | log.LstdFlags)
	var port = 2180
	var host = "0.0.0.0"

	flag.IntVar(&port, "p", port, "同 -port")
	flag.IntVar(&port, "port", port, "端口")
	flag.Parse()

	s := &http.Server{
		Addr:           fmt.Sprintf("%s:%d", host, port),
		Handler:        proxy.New(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer cancel()

	go func() {
		select {
		case <-ctx.Done():
			_ = s.Shutdown(context.TODO())
		}
	}()

	log.Println("启动:", s.Addr)
	if err := s.ListenAndServe(); err != nil {
		log.Fatal(err)
	}
	log.Println("退出")
}
